import 'package:flutter/material.dart' hide TabBar;
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/tabBar/kq_tabs.dart';
import '../../config/kq_global.dart';
import '../../resources/kq_theme_colors.dart';

import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../tagView/kq_number_tag_view.dart';
import 'kq_number_tab.dart';

/// 指示器类型
enum IndicatorType {
  ///下划线
  underline,

  ///圆形背景
  roundBg
}

/// 通用 TabBar
///
/// @author 周卓
///
class KqTabBar extends StatefulWidget {
  /// 指示器类型，0：下划线，1：圆形背景
  final IndicatorType indicatorType;

  /// 支持器大小
  final TabBarIndicatorSize? indicatorSize;

  /// TabController
  final TabController? tabController;

  /// Tab数据，包括标题和角标，以及是否显示角标
  final List<TabDataEntity> items;

  /// 自定义TabBar右侧控件，比如管理Tab的菜单
  final Widget? customTabRightView;

  /// 是否可水平滚动，否则均分
  final bool scrollable;

  /// Tab切换回调
  final ValueChanged<int>? onTap;

  /// 文字颜色和下划线颜色处理器，下划线颜色跟随选中的文字颜色，如果不设置，默认使用[_KqTabBarState._defaultTextColorBuilder]
  final Color? Function(
          IndicatorType indicatorType, bool selected, Color defColor)?
      textColorBuilder;

  /// 文字颜色和下划线颜色处理器，下划线颜色跟随选中的文字颜色，如果不设置，默认使用[_KqTabBarState._defaultUnderlineColorBuilder]
  final Color? Function(IndicatorType indicatorType, Color defColor)?
      underlineColorBuilder;

  /// 字体大小处理器，如果不设置，默认使用[_KqTabBarState._defaultFontSizeBuilder]
  final double Function(IndicatorType indicatorType, bool selected)?
      fontSizeBuilder;

  /// Tab背景颜色，针对 [IndicatorType.roundBg] 类型，选中时的颜色，默认跟随主题亮色
  final Color? roundBgColor;

  /// 角标最大数字，超过显示"[tagMaxNumber]+"，默认99
  final int tagMaxNumber;

  /// 是否隐藏底部分割线
  final bool hideDivider;

  /// 底部分割线颜色
  final Color? dividerColor;

  /// 默认选中位置，默认0，仅在[tabController]没传时生效
  final int initialIndex;

  /// 背景颜色
  final Color? backgroundColor;

  const KqTabBar(
      {Key? key,
      required this.items,
      this.tabController,
      this.indicatorType = IndicatorType.underline,
      this.indicatorSize,
      this.textColorBuilder,
      this.underlineColorBuilder,
      this.customTabRightView,
      this.fontSizeBuilder,
      this.tagMaxNumber = 99,
      this.initialIndex = 0,
      this.roundBgColor,
      this.backgroundColor,
      this.scrollable = false,
      this.hideDivider = false,
      this.dividerColor,
      this.onTap})
      : super(key: key);

  @override
  _KqTabBarState createState() => _KqTabBarState();
}

class _KqTabBarState extends State<KqTabBar> with TickerProviderStateMixin {
  /// 默认字体大小处理器
  double _defaultFontSizeBuilder(IndicatorType indicatorType, bool selected) {
    if (indicatorType == IndicatorType.underline) {
      //underline
      return 24.sp;
    } else {
      //roundBg
      return 20.sp;
    }
  }

  /// 默认文字颜色处理器
  Color _defaultTextColorBuilder(
      IndicatorType indicatorType, bool selected, Color defColor) {
    if (indicatorType == IndicatorType.underline) {
      //underline
      return selected
          ? (KqThemeManager.instance.getConfig().commonConfig.mainColor ??
              KqThemeColors.bgBlue)
          : defColor;
    } else {
      //roundBg
      return selected ? KqThemeColors.textWhite : defColor;
    }
  }

  /// 默认下划线颜色处理器
  Color _defaultUnderlineColorBuilder(
      IndicatorType indicatorType, Color defColor) {
    return defColor;
  }

  @override
  Widget build(BuildContext context) {
    TabBarIndicatorSize indicatorSize = widget.indicatorSize ??
        (widget.indicatorType == IndicatorType.underline
            ? TabBarIndicatorSize.tab
            : TabBarIndicatorSize.label);
    return ClipRect(
      child: Column(
        children: [
          Container(
            color: widget.backgroundColor ?? Colors.white,
            child: Row(
              children: [
                Expanded(
                    child: Container(
                        height: 64.r,
                        padding: EdgeInsets.symmetric(
                            vertical:
                                widget.indicatorType == IndicatorType.underline
                                    ? 0
                                    : 8.r,
                            horizontal:
                                widget.indicatorType == IndicatorType.underline
                                    ? 0
                                    : 16.r),
                        child: TabBar(
                            //选中的文字颜色
                            labelColor: _textColor(true),
                            //选中的文字样式
                            labelStyle: TextStyle(
                                color: _textColor(true),
                                fontSize: _fontSize(true)),
                            //未选中的文字颜色
                            unselectedLabelColor: _textColor(false),
                            //未选中的文字样式
                            unselectedLabelStyle: TextStyle(
                                color: _textColor(false),
                                fontSize: _fontSize(false)),
                            controller: widget.tabController ??
                                TabController(
                                    initialIndex: widget.initialIndex,
                                    length: widget.items.length,
                                    vsync: this),
                            isScrollable:
                                widget.scrollable || KqGlobal.tabBarScrollable,
                            indicatorWeight:
                                widget.indicatorType == IndicatorType.underline
                                    ? 2.r
                                    : 0,
                            indicatorSize: indicatorSize,
                            indicatorPadding: widget.indicatorType ==
                                        IndicatorType.underline ||
                                    indicatorSize == TabBarIndicatorSize.tab
                                ? EdgeInsets.zero
                                : EdgeInsets.symmetric(horizontal: -35.r),
                            labelPadding: _scrollable()
                                ? EdgeInsets.symmetric(horizontal: 35.r)
                                : EdgeInsets.zero,
                            onTap: widget.onTap,
                            tabs: widget.items
                                .map((e) => KqNumberTab(
                                      text: e.title,
                                      top: 0,
                                      numberBuilder: () => e.hideNumber
                                          ? Container()
                                          : KqNumberTagView(
                                              number: e.number,
                                              minSize: 18.r,
                                              fontSize: 12.sp,
                                              backgroundColor: _tagBgColor(),
                                              max: widget.tagMaxNumber,
                                            ),
                                    ))
                                .toList(),
                            indicator: widget.indicatorType ==
                                    IndicatorType.underline
                                ? UnderlineTabIndicator(
                                    borderSide: BorderSide(
                                        width: 2.r,
                                        // 下划线颜色
                                        color: _underlineColor()),
                                  )
                                : BoxDecoration(
                                    //圆形背景颜色
                                    color: _roundBgColor(),
                                    borderRadius: BorderRadius.all(Radius.circular(3.r)))))),
                widget.customTabRightView == null
                    ? Container()
                    : widget.customTabRightView!
              ],
            ),
          ),
          if (!widget.hideDivider)
            KqDivider(color: widget.dividerColor ?? KqThemeColors.lineColor)
        ],
      ),
    );
  }

  _scrollable() {
    return widget.scrollable || KqGlobal.tabBarScrollable;
  }

  /// 文字颜色
  _fontSize(bool selected) {
    return widget.fontSizeBuilder == null
        ? _defaultFontSizeBuilder(widget.indicatorType, selected)
        : widget.fontSizeBuilder!(widget.indicatorType, selected);
  }

  /// 文字颜色
  _textColor(bool selected) {
    return widget.textColorBuilder == null
        ? _defaultTextColorBuilder(
            widget.indicatorType, selected, KqThemeColors.textBlack85)
        : widget.textColorBuilder!(
            widget.indicatorType, selected, KqThemeColors.textBlack85) ?? KqThemeColors.textBlack85;
  }

  /// 下划线颜色
  _underlineColor() {
    return widget.underlineColorBuilder == null
        ? _defaultUnderlineColorBuilder(
            widget.indicatorType, KqThemeManager.instance.getConfig().commonConfig.mainColor ??
        KqThemeColors.bgBlue)
        : widget.underlineColorBuilder!(
            widget.indicatorType, KqThemeManager.instance.getConfig().commonConfig.mainColor ??
        KqThemeColors.bgBlue) ?? KqThemeManager.instance.getConfig().commonConfig.mainColor ??
        KqThemeColors.bgBlue;
  }

  /// 角标背景颜色
  _tagBgColor() {
    return widget.indicatorType == IndicatorType.underline
        ? _underlineColor()
        : _roundBgColor();
  }

  /// 圆背景颜色
  _roundBgColor() {
    return widget.roundBgColor ??
        (KqThemeManager.instance.getConfig().commonConfig.mainColor ??
            KqThemeColors.textBlue);
  }
}

/// Tab数据填充
class TabDataEntity {
  /// 标题
  String title;

  /// 数字角标
  int number;

  /// 是否隐藏角标
  bool hideNumber;

  /// 额外数据，备用
  dynamic extraData;

  TabDataEntity(this.title,
      {this.number = 0, this.hideNumber = false, this.extraData});
}
